package stack;

import java.util.Scanner;

public class ArrayStackDemo {
    public static void main(String[] args) {
        ArrayStack stack = new ArrayStack(4);
        String key = "";
        Scanner scanner = new Scanner(System.in);
        boolean loop = true;

        while (loop) {
            System.out.println("push: 入栈");
            System.out.println("pop: 出栈");
            System.out.println("show: 遍历栈");
            System.out.println("exit: 退出");
            key = scanner.next();
            switch (key) {
                case "push":
                    System.out.println("输入一个数");
                    int value = scanner.nextInt();
                    stack.push(value);
                    break;
                case "pop":
                    try {
                        System.out.println(stack.pop());
                        break;
                    } catch (Exception e) {
                        System.out.println(e.getMessage());
                    }
                case "show":
                    stack.show();
                    break;
                case "exit":
                    System.exit(0);
            }
        }
        scanner.close();
    }
}

class ArrayStack {
    private int maxSize;
    private int[] arr;
    private int top = -1;

    ArrayStack(int maxSize) {
        this.maxSize = maxSize;
        this.arr = new int[maxSize];
    }

    // 判断栈是否满
    public boolean isFull() {
        return top == maxSize - 1;
    }

    // 判断栈是否空
    public boolean isEmpty() {
        return top == -1;
    }

    // 入栈
    public void push(int v) {
        if (isFull()) {
            System.out.println("栈满");
            return;
        }
        arr[++top] = v;
    }

    // 出栈
    public int pop() {
        if (isEmpty()) {
            throw new RuntimeException("栈空");
        }
        return arr[top--];
    }

    // 输出栈
    public void show() {
        for (int i = top; i >= 0; i--) {
            System.out.println(arr[i]);
        }
    }
}